﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraTab;
using DevExpress.XtraTreeList.Nodes;
using MicropleSoft.Common.Library;
using MicropleSoft.Controls.DialogBox;
using MicropleSoft.WmsApp.Base.Menu;
using MicropleSoft.WmsApp.Base.Window;
using MicropleSoft.WmsApp.Library.Proxy;
using MicropleSoft.WmsApp.Library.ServiceFacade;

namespace MicropleSoft.WmsApp.BaseDataManage
{
    public partial class XBaseDataChild : BaseDataUserControl
    {
        private DataTableWrap _dataTableWrap = null;
        private List<ItemNode> _itemNodes = null;
        private ItemClass _itemClass = null;
        private List<ItemTemplate> _itemTemplates = null;
        private  string _classNumber = string.Empty;
        public XBaseDataChild()
        {
            InitializeComponent();
            RegisterTreeListNodeRelateForm();
            this.CmdNew.Click += new EventHandler(CmdNew_Click);
            this.CmdSave.Click += new EventHandler(CmdSave_Click);
        }

        private XtraTabPage ParentTabPage
        {
            get
            {
                if(this.Parent is XtraTabPage)
                    return (XtraTabPage) this.Parent;
                return null;
            }
        }

        private BaseForm FindParentForm()
        {
            return (BaseForm) this.FindForm();
        }

        public override void LoadTreeItem(string classNumber)
        {
            this._classNumber = classNumber;
            var list = ServerProxy.Query<ItemClass>("GetItemClassList", String.Format(" and CLASS_NUMBER= '{0}' ", _classNumber));
            if (list.Count == 0)
                return;
            _itemClass = list[0];
            LoadTreeList(_itemClass.ClassId);
        }

        /// <summary>
        /// 加载树形结构
        /// </summary>
        /// <param name="classId"></param>
        private void LoadTreeList(int classId)
        {
            _itemNodes = ServerProxy.Query<ItemNode>("GetItemNodeList", String.Format(" and NODE_CLASS= {0} ", classId));

            InitButtons();

            TreeListBinder.LoadTreeList(this.xTreeListMain,classId,_itemNodes);
        }

        private void InitButtons()
        {
            this.CmdNew.Text = string.Format(this.CmdNew.Text, _itemClass.ClassName);
            this.CmdNew.AutoSize = true;

            this.CmdSave.Text = string.Format(this.CmdSave.Text, _itemClass.ClassName);
            this.CmdSave.AutoSize = true;
        }

        private void CmdSave_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateData(_itemTemplates, _dataTableWrap.GetChanges().FDataTable);
                ServerProxy.CallService("SaveStaticDataTable", _dataTableWrap.GetChanges());
                _dataTableWrap.AcceptChanges();
            }
            catch (Exception exception)
            {
                CustomMessageBox.ShowError(exception.Message);
            }
           
        }

        private void ValidateData(List<ItemTemplate> itemTemplates,DataTable dataTable)
        {
            foreach (var itemTemplate in itemTemplates)
            {
                if (itemTemplate.ColumnType != null && 
                    (int)itemTemplate.ColumnType == ConstFlags.ColumnType4Varchar)
                {
                    foreach (DataRow dataRow in dataTable.Rows)
                    {
                        if (dataRow[itemTemplate.ColumnName] != DBNull.Value)
                        {
                            string val = dataRow[itemTemplate.ColumnName].ToString();
                            if (System.Text.Encoding.Default.GetByteCount(val) > itemTemplate.Length)
                            {
                                string exception = "字段{0}的值“{1}”超出了允许的范围，该字段最大允许长度为{2}！";
                                exception = string.Format(exception, itemTemplate.Caption, val, itemTemplate.Length);
                                throw new Exception(exception);
                            }
                        }
                    }
                }
            }
        }

        private void CmdNew_Click(object sender, EventArgs e)
        {
            if (_dataTableWrap == null)
                return;
            DataRow dr = _dataTableWrap.FDataTable.NewRow();
            foreach (var itemTemplate in _itemTemplates)
            {
                //如果是主键，则从服务器取下来赋予他。
                
                if(Constant.BaseDataCommonPrimaryField.Find(k=>String.Compare( k.PrimaryKeyName , itemTemplate.ColumnName,true) == 0) != null)
                {
                    int maxValue = (int)ServerProxy.CallService("GetMaxValue", _dataTableWrap.FItemClass.ItemTablename);
                    dr[itemTemplate.ColumnName] = maxValue;
                    continue;
                }

                //赋予父节点字段
                if (itemTemplate.ColumnName == "PARENT_ID")
                {
                    if (this.xTreeListMain.FocusedNode != null && this.xTreeListMain.FocusedNode.Tag != null)
                    {
                        var model = this.xTreeListMain.FocusedNode.Tag as ItemNode;
                        dr["PARENT_ID"] = model.NodeId;
                        continue;
                    }
                }

                if(itemTemplate.MustInput != null )
                {
                    if(ConstFlags.IsYes == (int) itemTemplate.MustInput)
                    {
                        //此处赋予默认值的问题，以后做考虑
                        switch (itemTemplate.ColumnType)
                        {
                            case ConstFlags.ColumnType4Varchar:
                                dr[itemTemplate.ColumnName] = "";
                                break;
                            case ConstFlags.ColumnType4Int:
                                dr[itemTemplate.ColumnName] = 0;
                                break;
                            case ConstFlags.ColumnType4DateTime:
                                dr[itemTemplate.ColumnName] = DateTime.Now;
                                break;
                            case ConstFlags.ColumnType4Number:
                                dr[itemTemplate.ColumnName] = 0;
                                break;
                            case ConstFlags.ColumnType4Bool:
                                dr[itemTemplate.ColumnName] = 0;
                                break;
                            default:
                                
                                break;
                        }
                    }
                }
            }
            _dataTableWrap.FDataTable.Rows.Add(dr);
            this.xGridControlData.RefreshDataSource();
        }

        private void RegisterTreeListNodeRelateForm()
        {
            this.xTreeListMain.AfterFocusNode += (o, e) =>
            {
                if (this.xTreeListMain.FocusedNode != null)
                {
                    var model = this.xTreeListMain.FocusedNode.Tag as ItemNode;
                    AfterSelectedNode(model);
                }
            };
        }

        private void AfterSelectedNode(ItemNode itemNode)
        {
           
            if (itemNode == null)
            {
                _dataTableWrap =
                    (DataTableWrap) ServerProxy.CallService("GetStaticDataTableWrapByItemClass", _itemClass.ClassNumber);
            }
            else
            {
                string condition = " and PARENT_ID = {0}";
                _dataTableWrap =
                    (DataTableWrap)
                    ServerProxy.CallService("GetStaticDataTableWrapByItemClass2", _itemClass.ClassNumber,
                                            string.Format(condition, itemNode.NodeId));
            }

            _itemTemplates = ServerProxy.Query<ItemTemplate>("GetItemTemplateList",
                                                         String.Format(" and TEMPLATE_ID= {0} ",_itemClass.ClassId));

            ParentTabPage.Text = _dataTableWrap.FItemClass.ClassName;

            int index = 0;
            //给XGridControl加字段
            foreach (var itemTemplate in _itemTemplates)
            {
                if (itemTemplate.IsVisable!= ConstFlags.IsYes)
                {
                    continue;
                }

                if (this.gridViewData.Columns.ColumnByFieldName(itemTemplate.ColumnName) == null)
                {
                    var gridColumn = new GridColumn();
                    gridColumn.Caption = itemTemplate.Caption;
               
                    RepositoryItem repositoryItem = null;
                    //此处赋予默认值的问题，以后做考虑
                    switch (itemTemplate.ColumnType)
                    {
                        case ConstFlags.ColumnType4Varchar:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().
                                                                                          GetRepositoryItemText(
                                                                                              itemTemplate.Length)
                                                                                  });
                            break;
                        case ConstFlags.ColumnType4Int:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().
                                                                                          GetRepositoryItem0DotDecimalPlaces
                                                                                          (0)
                                                                                  });
                            break;
                        case ConstFlags.ColumnType4DateTime:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().GetRepositoryItemDate()
                                                                                  });
                            break;
                        case ConstFlags.ColumnType4Number:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().
                                                                                          GetRepositoryItem0DotDecimalPlaces
                                                                                          (itemTemplate.NumberLength)
                                                                                  });
                            break;
                        case ConstFlags.ColumnType4Bool:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().
                                                                                          GetRepositoryItemCheckEdit()
                                                                                  });
                            break;
                        default:
                            gridViewData.GridControl.RepositoryItems.AddRange(new RepositoryItem[]
                                                                                  {
                                                                                      repositoryItem =
                                                                                      FindParentForm().
                                                                                          GetRepositoryItemText(
                                                                                              itemTemplate.Length)
                                                                                  });
                            break;
                    }
                    
                    gridColumn.FieldName = itemTemplate.ColumnName;

                    if(itemTemplate.ListIndex != null)
                    {
                         gridColumn.VisibleIndex = (int)itemTemplate.ListIndex;
                    }

                    if (itemTemplate.Length != null)
                    {
                        gridColumn.Width = (int)itemTemplate.Length*3;
                    }
                   
                    this.gridViewData.Columns.Add(gridColumn);
                    if (repositoryItem != null)
                    {
                        gridColumn.ColumnEdit = repositoryItem;
                    }
                }
            }

            this.xGridControlData.DataSource = _dataTableWrap.FDataTable;

        }
    }
}
